/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cheapflix.controller;

import com.cheapflix.beans.DVD;
import com.cheapflix.beans.RecommendedDVD;
import com.cheapflix.beans.User;
import com.cheapflix.beans.UserDVD;
import com.cheapflix.dao.DVDDao;
import com.cheapflix.dao.UserDAO;
import com.cheapflix.dao.UserDVDDao;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * Controller class in charge of the various user-level activities.
 * @author Group B
 */
@Controller
public class UserController {

    private static final Logger logger = Logger.getLogger(UserController.class);
    private UserDAO userDao;
    private DVDDao ddao;
    private UserDVDDao uddao;

    @Autowired
    public void init(UserDAO userDao, DVDDao ddao, UserDVDDao uddao) {
        this.userDao = userDao;
        this.ddao = ddao;
        this.uddao = uddao;
    }

    /**
     * Get a specific user's settings, if the user we want is "me" say so, 
     * the view will provide more "modifiable" content.
     */
    @RequestMapping("/users/{userId}")
    public ModelAndView GetUserSettings(@PathVariable("userId") int userId, HttpSession session) {
        User myUser = (User) session.getAttribute("me");
        if (myUser == null) {
            return new ModelAndView("redirect:/");
        }
        logger.info("user ID: " + userId);
        logger.info("HTTP Session: " + session);
        User thisUser = userDao.getUser(userId);
        for (String recommendedDVD : thisUser.getRecommendedDVDs().keySet()) {
            List<RecommendedDVD> recommendedDVDs = thisUser.getRecommendedDVDs().get(recommendedDVD);
            DVD dvd = ddao.getDVD(Integer.parseInt(recommendedDVD));
            for (RecommendedDVD rdvd : recommendedDVDs) {
                rdvd.setDVD(dvd);
            }
        }
        logger.info("ThisUser: " + thisUser);
        ModelAndView mav = new ModelAndView();

        if (thisUser.getId() != myUser.getId()) {
            if (myUser.getFriend(userId + "") == null) {
                mav.addObject("isFriend", false);
            } else {
                mav.addObject("isFriend", true);
            }
        }
        Set<DVD> recommendedDVDs = new HashSet<DVD>();
        for (String key : thisUser.getRecommendedDVDs().keySet()) {
            if (thisUser.getRecommendedDVDs().get(key) != null && thisUser.getRecommendedDVDs().get(key).size() > 0) {
                recommendedDVDs.add(thisUser.getRecommendedDVDs().get(key).get(0).getDvd());
            }

        }
        mav.addObject("recommendedDVDs", recommendedDVDs);
        mav.addObject("user", thisUser);
        mav.addObject("sameUser", thisUser.getId() == myUser.getId());

        mav.setViewName("UserProfile");
        return mav;
    }

    /**
     * Unfriend a user.
     * @param userId user who we want to unfriend.
     * @param session session variable used to get logged in user.
     * @return ModelAndView
     */
    @RequestMapping("/unfriend/{userId}")
    public ModelAndView Unfriend(@PathVariable("userId") int userId, HttpSession session) {
        logger.info("Inside Unfriend handler");
        User me = (User) session.getAttribute("me");
        if (me == null) {
            return new ModelAndView("redirect:/");
        }
        int meId = me.getId();
        userDao.removeFriend(meId, userId);
        User thisUser = userDao.getUser(userId);
        ModelAndView mav = new ModelAndView();
        mav.addObject("user", thisUser);
        mav.setViewName("redirect:/users/" + meId);
        return mav;
    }

    /**
     * Search for users 
     */
    @RequestMapping("/usersearch")
    public ModelAndView UserSearch(@RequestParam("q") String criteria) {
        return searchuser(criteria);
    }

    private ModelAndView searchuser(String criteria) {
        ModelAndView mav = new ModelAndView();
        if (criteria != null) {
            Set<User> usersFound = userDao.SearchUsers(criteria);
            mav.addObject("result", usersFound);
        }
        mav.setViewName("UserSearch");
        return mav;
    }

    /**
     * Friend a user.
     * @param userId user to friend
     * @param session session variable.
     * @return ModelAndView
     */
    @RequestMapping("/frienduser/{userId}")
    public ModelAndView FriendUser(@PathVariable("userId") int userId, HttpSession session) {
        User me = (User) session.getAttribute("me");
        if (me == null) {
            return new ModelAndView("redirect:/");
        }
        int myId = me.getId();
        userDao.addAsFriend(myId, userId);
        User newMe = userDao.getUser(myId);
        session.setAttribute("me", newMe);
        ModelAndView mav = new ModelAndView();
        mav.setViewName("redirect:/users/" + userId);
        return mav;
    }

    /**
     * Get a user's queue
     */
    @RequestMapping("/UserQueue/{userId}")
    public ModelAndView UserQueue(@PathVariable("userId") int userId, HttpSession session) {
        List<UserDVD> queueDVDs = uddao.getUserDVDQueue(userId);
        User user = userDao.getUser(userId);
        ModelAndView mav = new ModelAndView();
        mav.addObject("user", user);
        mav.addObject("queueDVDs", queueDVDs);
        mav.setViewName("UserQueue");
        return mav;
    }

    /**
     * Update user's information
     */
    @RequestMapping(value = "/updateuserinfo/", method = RequestMethod.POST)
    public ModelAndView FriendUser(
            @RequestParam("userId") int userId,
            @RequestParam("nameFirst") String nameFirst,
            @RequestParam("nameLast") String nameLast,
            @RequestParam("password") String password) {
        userDao.updateUserInfo(userId, nameFirst, nameLast, password);
        ModelAndView mav = new ModelAndView();
        mav.addObject("msg", "User updated successfully");
        mav.setViewName("redirect:/users/" + userId);
        return mav;
    }
}
